<?php
// +----------------------------------------------------------------------
// | 阿里云
// +----------------------------------------------------------------------

namespace helper\storage\driver;

use helper\storage\Driver;
use OSS\OssClient;
use OSS\Core\OssException;

/**
 * 阿里云oss
 */
class Oss implements Driver
{
    private array $config;

    private $handler;

    public function __construct($config)
    {
        $this->config  = $config;
        $this->handler = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
    }

    /**
     * 上传文件
     * @param string $object
     * @param string $filePath
     * @return array
     */
    public function putFile(string $object, string $filePath): array
    {
        try {
            $filePath = $filePath . '/' . $object;
            $fileSize = filesize($filePath);
            if ($fileSize < 20 * 1024 * 1024) {
                $result = $this->handler->uploadFile($this->config['bucket'], $object, $filePath);
            } else {
                $options = array(
                    OssClient::OSS_CHECK_MD5 => true,
                    OssClient::OSS_PART_SIZE => 1,
                );
                $result = $this->handler->multiuploadFile($this->config['bucket'], $object, $filePath, $options);
            }
            return ['code' => 0, 'msg'=> '', 'data' => $result];
        } catch(OssException $e) {
            return ['code' => 1, 'msg'=> $e->getMessage()];
        }
    }

    /**
     * 删除远程文件
     * @param string $object
     * @return array
     */
    public function deleteFile(string $object): array
    {
        $result = $this->handler->deleteObject($this->config['bucket'], $object);
        return ['code' => 0, 'msg'=> '', 'data' => $result];
    }
}